home *** CD-ROM | disk | FTP | other *** search
/ NetNews Offline 2 / NetNews Offline Volume 2.iso / news / comp / lang / c-part1 / 3844 < prev    next >
Encoding:
Internet Message Format  |  1996-08-05  |  1.9 KB

  1. Path: news.lpr.carel.fi!usenet
  2. From: Ari Lukumies <aril@cmt.lpr.mail.carel.fi>
  3. Newsgroups: comp.lang.c
  4. Subject: Re: How to give functions as parameters?
  5. Date: Wed, 31 Jan 1996 16:11:10 +0200
  6. Organization: Carelcomp Forest
  7. Message-ID: <310F787E.7B14@cmt.lpr.mail.carel.fi>
  8. References: <Pine.SUN.3.91N2x.960130222756.11581A-100000@yellow59.nada.kth.se>
  9. NNTP-Posting-Host: renoir.cclahti.carel.fi
  10. Mime-Version: 1.0
  11. Content-Type: text/plain; charset=us-ascii
  12. Content-Transfer-Encoding: 7bit
  13. X-Mailer: Mozilla 2.0b6a (WinNT; I)
  14.  
  15. Per Steneskog wrote:
  16. > I have a little problem, I dont know how to send a fuction,
  17. > as a parameter to another function..
  18. > #include <stdio.h>
  19. > void
  20. > do_it(void (*it)())
  21.  
  22. You are expecting a pointer to a function returning void...
  23.  
  24. > {
  25. >   ((*(it))());
  26.  
  27. Too much to type, just use
  28.     (*it)();
  29. > }
  30. > void
  31. > do_me(
  32. >       void)
  33. > {
  34. >   printf("Testing!");
  35. > }
  36. > int
  37. > main(
  38. >      void)
  39. > {
  40. >   do_it(do_me()); /* ERROR-COMPILE LINE */
  41.  
  42. You are calling do_it and passing to it the return value of do_me, which is 
  43. nothing (first, do_me gets executed, the return value, none in this case, is then 
  44. passed as a parameter to do_it). Change the line to read:
  45.  
  46.     do_it(do_me);
  47.  
  48. which will get the address of do_me passing that to do_it. do_it will then 
  49. correctly call do_me.
  50. > }
  51. > Short explaination: From main(), do_it() should be called with
  52. > the parameter (and function) do_me(). (Pretty obvious :)
  53.  
  54. To make it clear, you cannot pass a function to a function. You _can_ pass the 
  55. address (pointer) or the return value of a function.
  56.  
  57. > When I try to compile this, i got the following error message: (gcc)
  58. >         In function `main':
  59. >         invalid use of void expression
  60. > My question is, what should I write instead of that line in main()?
  61. > THANKS everyone out there!
  62.  
  63. You're welcome.
  64.  
  65. Later,
  66. AriL
  67. -- 
  68. All my opinions are mine and mine alone.
  69.